package com.chinackts.config.interceptor;

import com.chinackts.auth.repository.redis.ICCardRepository;
import com.chinackts.auth.repository.redis.SocialCreditCodeRepository;
import com.chinackts.common.utils.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author Lianhong
 * @since 2022/3/29
 */
@Component
public class RequestInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestInterceptor.class);

    @Resource
    private StringRedisTemplate redisTemplate1;
    @Resource
    private ICCardRepository icCardRepository;
    @Resource
    private SocialCreditCodeRepository socialCreditCodeRepository;
    @Value("${e-port.redis.timeout}")
    private long timeout;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String id = RequestUtil.getRequestId(request);
        Set<String> keys = redisTemplate1.keys(id + ":*");
        MDC.put("SID", id);
        //ID下keys不为空，并且存在icCard（口岸卡号）、socialCreditCode（组织机构代码），表示ID尚未失效
        if (!CollectionUtils.isEmpty(keys)
                && keys.contains(icCardRepository.key(id))
                && keys.contains(socialCreditCodeRepository.key(id))) {
            //用户登录标识缓存信息还未过期，则重置失效时间
            keys.forEach(k -> redisTemplate1.expire(k, timeout, TimeUnit.HOURS));
            return true;
        }
        //ID失效，清除ID下所有缓存信息
        if (keys != null) redisTemplate1.delete(keys);
        LOGGER.warn("用户标识【{}】已失效", id);
        response.setStatus(401);
        return false;
    }
}
